package com.data.mall.controller;

import com.data.mall.controller.vo.ItemVO;
import com.data.mall.data.service.DataCollectService;
import com.data.mall.exception.BusinessException;
import com.data.mall.exception.ResponseCodeEnum;
import com.data.mall.service.CacheService;
import com.data.mall.service.ItemService;
import com.data.mall.service.PromoService;
import com.data.mall.service.dto.ItemDTO;
import com.data.mall.service.dto.UserDTO;
import com.data.mall.utils.http.Response;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PromoService promoService;

    @Autowired
    private DataCollectService dataCollectService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //创建商品的controller
    @PostMapping("/create")
    public Response createItem(@RequestParam(name = "title")String title,
                               @RequestParam(name = "description")String description,
                               @RequestParam(name = "price") String price,
                               @RequestParam(name = "stock")Integer stock,
                               @RequestParam(name = "imgUrl")String imgUrl) throws BusinessException {
        //封装service请求用来创建商品
        ItemDTO itemModel = new ItemDTO();
        itemModel.setTitle(title);
        itemModel.setDescription(description);
        itemModel.setPrice(price);
        itemModel.setStock(stock);
        itemModel.setImgUrl(imgUrl);

        ItemDTO itemModelForReturn = itemService.createItem(itemModel);
        ItemVO itemVO = convertVOFromModel(itemModelForReturn);

        return Response.getInstance(itemVO);
    }

    @RequestMapping(value = "/publishpromo",method = {RequestMethod.GET})
    @ResponseBody
    public Response publishpromo(@RequestParam(name = "id")Long id){
        promoService.publishPromo(id);
        return Response.ok();

    }
    //商品详情页浏览
    @RequestMapping(value = "/get",method = {RequestMethod.GET})
    @ResponseBody
    public Response getItem(@RequestParam(name = "id")Long id){
        // 校验登录并获取用户信息
        UserDTO user = checkAndGetUserInfo(httpServletRequest);
        ItemDTO itemModel = null;
        //先取本地缓存
        itemModel = (ItemDTO) cacheService.getFromCommonCache("item_"+id);

        if(itemModel == null){
            //根据商品的id到redis内获取
            itemModel = (ItemDTO) redisTemplate.opsForValue().get("item_"+id);

            //若redis内不存在对应的itemModel,则访问下游service
            if(itemModel == null){
                itemModel = itemService.getItemById(id);
                //设置itemModel到redis内
                redisTemplate.opsForValue().set("item_"+id,itemModel);
                redisTemplate.expire("item_"+id,10, TimeUnit.MINUTES);
            }
            //填充本地缓存
            cacheService.setCommonCache("item_"+id,itemModel);
        }


        ItemVO itemVO = convertVOFromModel(itemModel);
        // C端埋点
        dataCollectService.goodsDetailRecord(itemModel, user);
        return Response.getInstance(itemVO);

    }

    //商品列表页面浏览
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    @ResponseBody
    public Response listItem(){
        List<ItemDTO> itemModelList = itemService.listItem();

        //使用stream apiJ将list内的itemModel转化为ITEMVO;
        List<ItemVO> itemVOList =  itemModelList.stream().map(itemModel -> {
            ItemVO itemVO = this.convertVOFromModel(itemModel);
            return itemVO;
        }).collect(Collectors.toList());
        return Response.getInstance(itemModelList);
    }




    private ItemVO convertVOFromModel(ItemDTO itemModel){
        if(itemModel == null){
            return null;
        }
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel,itemVO);
        if(itemModel.getPromoDTO() != null){
            //有正在进行或即将进行的秒杀活动
            itemVO.setPromoStatus(itemModel.getPromoDTO().getStatus());
            itemVO.setPromoId(itemModel.getPromoDTO().getId());
            itemVO.setStartDate(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(itemModel.getPromoDTO().getStartTime()));
            itemVO.setPromoPrice(itemModel.getPromoDTO().getPromoItemPrice());
        }else{
            itemVO.setPromoStatus(0);
        }
        return itemVO;
    }

    /**
     * 获取用户登录信息
     */
    private UserDTO checkAndGetUserInfo(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getParameterMap().get("token")[0];
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(ResponseCodeEnum.PARAM_ERROR,"用户还未登陆，不能下单");
        }
        //获取用户的登陆信息
        UserDTO userModel = (UserDTO) redisTemplate.opsForValue().get(token);
        if(userModel == null){
            throw new BusinessException(ResponseCodeEnum.PARAM_ERROR,"用户还未登陆，不能下单");
        }
        return userModel;
    }
}